<?php
if (! defined ('IN_ZWS')) exit ();

class UAction extends Action {
	function _initialize() {
		$this -> assign('nowNav', 0);
		$setting = array_merge(json_decode(setting('mailSetting'), true), array('verifyDeathTime' => setting('verifyDeathTime'), 'mgrMail' => setting('mgrMail'), 'touclick' => json_decode(setting('touclickSetting'), true)));
		$this -> assign($setting);
		$this -> assign('siteName', setting('siteName'));
		$this -> assign('siteSubName', setting('siteSubName'));
		$this -> assign('siteDesc', setting('siteDesc'));
		$this -> assign('setting', $setting);
	}

	function index() {
		header('Location:' . __APP__ . '/u/login');
	}

	function login() {
		if (!empty($_SESSION['uid']) && !empty($_SESSION['ltime'])) {
			$info = D('InfoView');
			$userInfo = $info -> where("User.id=" . $_SESSION['uid']) -> find();
			$userInfo['avatar'] = array(300 => parseAvatar($userInfo['avatar']), 100 => parseAvatar($userInfo['avatar'], 100), 50 => parseAvatar($userInfo['avatar'], 50));
			if (empty($userInfo) || empty($userInfo['username']) || $_SESSION['ltime'] < $userInfo['cptime']) {
				unset ($_SESSION ['uid'], $_SESSION ['username'], $_SESSION ['ltime']);
				session ('[destroy]');
				session ('[regenerate]');
				$this -> display ();
				exit();
			}
			$this -> error("您已登录");
		}
		$this -> display ();
	}

	function reg() {
		if (!empty($_SESSION['uid']) && !empty($_SESSION['ltime'])) {
			$info = D('InfoView');
			$userInfo = $info -> where("User.id=" . $_SESSION['uid']) -> find();
			$userInfo['avatar'] = array(300 => parseAvatar($userInfo['avatar']), 100 => parseAvatar($userInfo['avatar'], 100), 50 => parseAvatar($userInfo['avatar'], 50));
			if (empty($userInfo) || empty($userInfo['username']) || $_SESSION['ltime'] < $userInfo['cptime']) {
				unset ($_SESSION ['uid'], $_SESSION ['username'], $_SESSION ['ltime']);
				session ('[destroy]');
				session ('[regenerate]');
				$this -> display ();
				exit();
			}
			$this -> error("您已登录");
		}
		$this -> display ();
	}

	function doLogin() {
		$verify = M ('UserVerify');
		if ($verify -> where ("username='" . $this -> _post ('username') . "' AND type=1") -> find ())
			$this -> error ('该邮箱尚未通过验证，若未收到验证邮件，请找回密码！');
		$user = D ('UserLogin');
		if ($user -> create ()) { // 创建
			$userinfo = $user -> where ("username='" . $this -> _post ('username') . "'") -> find ();
			if (! $userinfo)
				$userinfo = $user -> where ("email='" . $this -> _post ('username') . "'") -> find ();
			if ($userinfo) { // 检查是否有该帐号
				$loginfo = array ('uid' => $userinfo ['id'],
					'type' => 1,
					'ip' => $_SERVER ['REMOTE_ADDR'],
					'time' => time (),
					'status' => 0,/**
					 * 默认为未知状态
					 */
					); // 生成日志信息（不包括状态）
				$userpwd = md5 (md5 ($this -> _post ('password')) . $userinfo ['salt']); // 计算加密后的密码
				if ($userinfo ['password'] == $userpwd) { // 验证密码是否正确
					$loginfo ['status'] = 1; // 登录成功记录状态为1
					$this -> saveLog ($loginfo);
					$_SESSION ['uid'] = $loginfo ['uid'];
					$_SESSION ['ltime'] = time ();
					$expt = time () + 2592000;
					setcookie (session_name (), session_id (), $expt, '/');
					$_SESSION ['expt'] = $expt;
					if (IS_AJAX) $this -> ajaxReturn(array("redirect" => "/i"), "{$userinfo ['username']},欢迎回来~", 0);
					$this -> success ('登录成功', '/i');
				} else {
					$loginfo ['status'] = 2;
					$this -> saveLog ($loginfo);
					if (IS_AJAX) $this -> ajaxReturn('', "密码错误!", 1);
					$this -> error ('密码错误!'); // 登录失败记录状态为2
				}
			} else {
				if (IS_AJAX) $this -> ajaxReturn('', "帐号不存在!", 2);
				$this -> error ('帐号不存在!');
			}
		} else {
			if (IS_AJAX) $this -> ajaxReturn('', $user -> getError (), 2);
			$this -> error ($user -> getError ());
		}
	}

	function logout() {
		if (isEmpty($_SESSION['uid']) && isEmpty($_SESSION['ltime'])) $this -> error("您未登录，无需注销");
		unset ($_SESSION ['uid'], $_SESSION ['username'], $_SESSION ['ltime']);
		session ('[destroy]');
		session ('[regenerate]');
		$this -> success ('注销成功！', __URL__ . '/login');
	}

	function doReg() {
		$this -> checkVCode ();
		// 检查是否有未验证记录
		$verify = M ('UserVerify');
		if ($verify -> where ("username='" . $this -> _post ('username') . "'") -> find ()) $this -> error ('该用户名已被注册！');
		if ($verify -> where ("email='" . $this -> _post ('email') . "'") -> find ()) $this -> error ('该邮箱已被注册！');
		$user = D ('UserReg');
		if ($user -> create ()) {
			$data = $user -> getData ();
			$insert ['username'] = $data ['username'];
			$insert ['email'] = $data ['email'];
			$insert ['authcode'] = String :: randString (64);
			$insert ['time'] = time ();
			unset ($data ['username'], $data ['email']);
			$insert ['data'] = json_encode ($data);
			if ($verify -> add ($insert)) {
				sendVerifyMail ($insert, 1);
				$this -> assign ('waitSecond', 5);
				$this -> success ('注册成功，激活邮件已经发送给您，请点击激活邮件里的激活链接进行激活');
			} else {
				$this -> error ('注册失败');
			}
		} else {
			$this -> error ($user -> getError ());
		}
	}

	function resetpwd() {
		if (!empty($_SESSION['uid']) && !empty($_SESSION['ltime'])) {
			$info = D('InfoView');
			$userInfo = $info -> where("User.id=" . $_SESSION['uid']) -> find();
			$userInfo['avatar'] = array(300 => parseAvatar($userInfo['avatar']), 100 => parseAvatar($userInfo['avatar'], 100), 50 => parseAvatar($userInfo['avatar'], 50));
			if (empty($userInfo) || empty($userInfo['username']) || $_SESSION['ltime'] < $userInfo['cptime']) {
				unset ($_SESSION ['uid'], $_SESSION ['username'], $_SESSION ['ltime']);
				session ('[destroy]');
				session ('[regenerate]');
				$this -> display ();
				exit();
			}
			$this -> error("您已登录");
		}
		$this -> display ();
	}

	function doResetPwd() {
		$this -> checkVCode ();
		$verify = M ('UserVerify');
		$userreset = D ('UserReset');
		if ($userreset -> create ()) {
			if ($_SESSION ['authcode'] != null) { // 如果正在重设密码
				if (strtolower ($this -> _post ('username')) != strtolower ($_SESSION ['authusername'])) $this -> error ('要验证的帐号错误！');
				$verifyinfo = $verify -> where ("username='" . $_SESSION ['authusername'] . "' AND authcode='" . $_SESSION ['authcode'] . "'") -> find ();
				if (! $verifyinfo) $this -> error ('非法表单！');
				// 保存日志
				$user = M ('User');
				$userinfo = $user -> field ('id') -> where ("username='" . $_SESSION ['authusername'] . "'") -> find ();
				$loginfo = json_decode ($verifyinfo ['data'], true);
				$loginfo ['uid'] = $userinfo ['id'];
				$this -> saveLog ($loginfo);
				import ('ORG.Util.String');
				$salt = String :: randString (6);
				$password = md5 (md5 ($this -> _post ('password')) . $salt);
				$data = array ('password' => $password,
					'salt' => $salt,
					'cptime' => time ()
					);
				unset ($_SESSION ['authusername'], $_SESSION ['authcode']);
				$verify -> where ("username='" . $this -> _post ('username') . "'") -> delete ();
				$user -> where ("id='" . $userinfo ['id'] . "'") -> save ($data);
				$this -> assign ('waitSecond', 5);
				$this -> success ("重设密码成功，请使用新密码登录！", __URL__ . '/login');
			}
			$data = $userreset -> getData ();
			if (! $userreset -> where ("username='" . $this -> _post ('username') . "' AND email='" . $this -> _post ('email') . "'") -> find ()) {
				$notRegIn = $verify -> where ("username='" . $this -> _post ('username') . "' AND type=1") -> find ();
				if (! $notRegIn) $this -> error ('帐号与邮箱不对应！');
			}
			$verify -> where ("username='" . $this -> _post ('username') . "'") -> delete ();
			import ('ORG.Util.String');
			$insert = array ('username' => $this -> _post ('username'),
				'email' => $this -> _post ('email'),
				'authcode' => String :: randString (64),
				'time' => $data ['time'],
				'type' => 2,
				'data' => json_encode (array ('type' => 3,
						'ip' => $data ['ip'],
						'time' => $data ['time'],
						'status' => 1
						))
				);
			if ($notRegIn) { // 如果是新注册而未验证的
				$insert ['type'] = 1;
				$insert ['data'] = $notRegIn ['data'];
			}
			if ($verify -> add ($insert)) {
				sendVerifyMail ($insert, 2);
				$this -> assign ('waitSecond', 5);
				$this -> success ('验证邮件已发送到您的邮箱，请查收', __URL__ . '/login');
			} else {
				$this -> error ('申请重置失败，请重试');
			}
		} else {
			$this -> error ($userreset -> getError ());
		}
	}

	function verify() {
		$verify = M ('UserVerify');
		$verifyinfo = $verify -> where ("email='" . $this -> _get ('email') . "' AND authcode='" . $this -> _get ('authcode') . "'") -> find ();
		if (! $verifyinfo) $this -> error ('该链接不正确或已失效！');
		if (time () > $verifyinfo ['time'] + setting ('verifyDeathTime') * 60) {
			$verify -> where ("email='" . $this -> _get ('email') . "' AND authcode='" . $this -> _get ('authcode') . "'") -> delete ();
			$this -> error ('已超过验证时间，请重新申请验证！');
		}
		switch ($verifyinfo ['type']) {
			case 1 :
				$userinfo = json_decode ($verifyinfo ['data'], true);
				$userinfo ['username'] = $verifyinfo ['username'];
				$userinfo ['email'] = $verifyinfo ['email'];
				$this -> assign ('waitSecond', 3);
				$userinfo['info'] = array('sex' => 1);
				$userinfo['credit'] = array('credit' => 100);
				$D = D('User');
				if ($D -> relation(true) -> add($userinfo)) {
					$verify -> where ("email='" . $this -> _get ('email') . "' AND authcode='" . $this -> _get ('authcode') . "'") -> delete ();
					$this -> success ('恭喜您，验证通过！', __URL__ . '/login');
				}
				$this -> error('抱歉，验证失败', __URL__ . '/resetpwd');
				break;
			case 2 :
				$_SESSION ['authcode'] = $this -> _get ('authcode');
				$_SESSION ['authusername'] = $verifyinfo ['username'];
				$this -> assign ('setnow', 1);
				$this -> display ('resetpwd');
				break;
			case 3:
				$this -> assign ('waitSecond', 7);
				$verifyData = json_decode($verifyinfo['data'], true);
				if ($verifyData['step'] == 0) {
					import ('ORG.Util.String');
					$authcode = String :: randString (64);
					$insertData = array('id' => $verifyinfo['id'],
						'username' => $verifyinfo['username'],
						'email' => $verifyinfo['email'],
						'data' => json_encode(array('oldMail' => $verifyData['oldMail'], 'step' => 1)),
						'authcode' => $authcode,
						'time' => time(),
						);
					$verify -> save($insertData);
					sendVerifyMail($insertData, 4);
					$this -> success ('恭喜您通过第一次验证！已将第二封验证邮件发送到您的新邮箱中，请注意查收', __APP__ . '/');
				} elseif ($verifyData['step'] == 1) {
					$user = M('user');
					$userinfo = $user -> where(array('username' => $verifyinfo['username'],)) -> find();
					if ($verify -> table('zws_user') -> save(array('id' => $userinfo['id'], 'email' => $verifyinfo['email'], 'cptime' => time()))) {
						$user -> table('zws_user_log') -> add(array('uid' => $userinfo['id'], 'type' => 5, 'ip' => $_SERVER["REMOTE_ADDR"], 'time' => time(), 'status' => 1));
						$verify -> delete($verifyinfo['id']);
					}
					$this -> success ('恭喜您通过第二次验证！您的邮箱已被成功修改！', __APP__ . '/i/');
				}
				break;
		}
	}

	protected function checkVCode() {
		import ('ORG.Util.Touclick');
		if (! $_POST ['check_key'] || ! $_POST ['check_address']) $this -> error ("验证码必须！");
		$touclickSetting = json_decode(setting('touclickSetting'), true);
		$touclick = new touclick ();
		$res = $touclick -> touclickCheck ($touclickSetting['publicKey'], $touclickSetting['privateKey'], $_POST ['check_key'], $_POST ['check_address']);
		if (! $res) $this -> error ('验证码二次验证未通过，请重来一次');
	}

	protected function saveLog($data) {
		$log = M ('UserLog');
		$log -> data ($data) -> add (); // 保存日志
	}
}
